const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义价格历史记录的 schema
const priceHistorySchema = {
  date: { type: Date, required: true },
  marketPrice: { type: Number, default: 0 },
  purchasePrice: { type: Number, default: 0 },
  shareRatio: { type: Number, default: 0.3 },
  recoveryPrice: { type: Number, default: 0 },
  platformProfit: { type: Number, default: 0 },
  userProfit: { type: Number, default: 0 }
};

// 定义商品 schema
const productSchema = new Schema({
  id: { type: String, required: true, unique: true },
  name: { type: String, required: true },
  categoryId: { type: String, required: true },
  categoryName: { type: String, required: true },
  brandId: { type: String, required: true },
  brandName: { type: String, required: true },
  mainImage: { type: String },
  images: [{ type: String }],
  batchNo: { type: String },
  specification: { type: String },
  unit: { type: String },
  precautions: { type: String },
  remark: { type: String },
  sort: { type: Number, default: 0 },
  status: { type: Boolean, default: true },
  priceHistory: [priceHistorySchema]
}, {
  timestamps: true
});

// 获取指定日期范围的价格历史
productSchema.methods.getPriceHistory = function(startDate, endDate) {
  let filteredHistory = this.priceHistory;

  if (startDate || endDate) {
    filteredHistory = this.priceHistory.filter(record => {
      const recordDate = record.date.getTime();
      const start = startDate ? new Date(startDate).getTime() : -Infinity;
      const end = endDate ? new Date(endDate).getTime() : Infinity;
      return recordDate >= start && recordDate <= end;
    });
  }

  return filteredHistory;
};

productSchema.statics = {
  createProduct: async function(productData) {
    try {
      // 生成唯一ID
      const timestamp = new Date().getTime();
      const random = Math.floor(Math.random() * 1000);
      const id = `${timestamp}${random}`;

      // 创建基础数据对象
      const baseData = {
        ...productData,
        id,
        images: Array.isArray(productData.images) ? productData.images : [productData.images],
        sort: Number(productData.sort) || 0,
        status: productData.status !== undefined ? Boolean(productData.status) : true
      };

      // 处理价格历史数据
      if (Array.isArray(productData.priceHistory)) {
        baseData.priceHistory = productData.priceHistory.map(item => ({
          date: new Date(item.date),
          marketPrice: Number(item.marketPrice) || 0,
          purchasePrice: Number(item.purchasePrice) || 0,
          shareRatio: Number(item.shareRatio) || 0.3,
          recoveryPrice: Number(item.recoveryPrice) || 0,
          platformProfit: Number(item.platformProfit) || 0,
          userProfit: Number(item.userProfit) || 0
        }));
      } else {
        baseData.priceHistory = [];
      }

      // 创建新商品
      const product = await this.create(baseData);
      return product;
    } catch (error) {
      console.error('创建商品错误:', error);
      throw error;
    }
  },

  updateProduct: async function(id, productData) {
    try {
      // 处理价格历史数据
      if (Array.isArray(productData.priceHistory)) {
        productData.priceHistory = productData.priceHistory.map(item => ({
          date: new Date(item.date),
          marketPrice: Number(item.marketPrice) || 0,
          purchasePrice: Number(item.purchasePrice) || 0,
          shareRatio: Number(item.shareRatio) || 0.3,
          recoveryPrice: Number(item.recoveryPrice) || 0,
          platformProfit: Number(item.platformProfit) || 0,
          userProfit: Number(item.userProfit) || 0
        }));
      }

      // 使用自定义 id 查找和更新
      const product = await this.findOneAndUpdate(
        { id: id },
        productData,
        { 
          new: true,
          runValidators: true
        }
      );

      if (!product) {
        throw new Error('Product not found');
      }

      return product;
    } catch (error) {
      console.error('Error updating product:', error);
      throw error;
    }
  },

  getProductForH5: async function(id) {
    try {
      const product = await this.findOne({ id });
      if (!product) {
        throw new Error('Product not found');
      }

      const productObj = product.toObject();

      // 处理价格历史数据，只保留需要的字段
      if (productObj.priceHistory && productObj.priceHistory.length > 0) {
        // 按日期排序，最新的在前
        productObj.priceHistory.sort((a, b) => new Date(b.date) - new Date(a.date));

        // 获取最新的价格记录作为今日参考行情
        const latestPrice = productObj.priceHistory[0];
        productObj.currentPrice = {
          date: latestPrice.date,
          purchasePrice: latestPrice.purchasePrice,
          recoveryPrice: latestPrice.recoveryPrice,
          userProfit: latestPrice.userProfit
        };

        // 只保留需要的字段
        productObj.priceHistory = productObj.priceHistory.map(item => ({
          date: item.date,
          purchasePrice: item.purchasePrice,
          recoveryPrice: item.recoveryPrice,
          userProfit: item.userProfit
        }));
      } else {
        productObj.currentPrice = null;
        productObj.priceHistory = [];
      }

      return productObj;
    } catch (error) {
      throw error;
    }
  },

  // 复制商品
  copyProduct: async function(id) {
    try {
      // 查找原商品
      const product = await this.findOne({ id });
      if (!product) {
        throw new Error('商品不存在');
      }

      // 创建新商品数据
      const newProduct = {
        ...product.toObject(),
        id: Date.now().toString(), // 生成新的ID
        name: `${product.name}(复制)`, // 修改名称
        sort: (product.sort || 0) + 1, // 排序号+1
        priceHistory: product.priceHistory ? [product.priceHistory[product.priceHistory.length - 1]] : [], // 只保留最新的价格历史
        createdAt: new Date(),
        updatedAt: new Date()
      };

      // 删除MongoDB的_id字段
      delete newProduct._id;

      // 创建新商品
      const createdProduct = await this.create(newProduct);
      return createdProduct;
    } catch (error) {
      console.error('复制商品失败:', error);
      throw error;
    }
  },

  // 获取H5商品列表
  getProductListForH5: async function(query = {}, pageSize = 10, pageNum = 1) {
    try {
      const { brandIds, categoryId, ...otherQuery } = query;
      
      // 构建查询条件
      const findQuery = {
        status: 1,
        ...otherQuery
      };
      
      // 如果提供了品牌ID数组，添加到查询条件
      if (Array.isArray(brandIds) && brandIds.length > 0) {
        findQuery.brandId = { $in: brandIds };
      }
      
      // 如果提供了分类ID，添加到查询条件
      if (categoryId) {
        findQuery.categoryId = categoryId;
      }

      // 查询商品列表
      const products = await this.find(findQuery)
        .sort({ sort: -1, _id: -1 })
        .skip((pageNum - 1) * pageSize)
        .limit(pageSize);

      // 获取总数
      const total = await this.countDocuments(findQuery);

      // 处理每个商品的价格历史
      const processedProducts = products.map(product => {
        const productObj = product.toObject();
        
        // 获取最新的价格历史记录
        if (productObj.priceHistory && productObj.priceHistory.length > 0) {
          // 按日期排序，获取最新记录
          productObj.priceHistory.sort((a, b) => new Date(b.date) - new Date(a.date));
          const latestPrice = productObj.priceHistory[0];
            
          // 将最新价格数据提取到根级别
          productObj.purchasePrice = latestPrice.purchasePrice;
          productObj.recoveryPrice = latestPrice.recoveryPrice;
          productObj.userProfit = latestPrice.userProfit;
          productObj.purchasePriceDate = latestPrice.date;
        } else {
          // 如果没有价格历史，设置默认值
          productObj.purchasePrice = 0;
          productObj.recoveryPrice = 0;
          productObj.userProfit = 0;
          productObj.purchasePriceDate = null;
        }
        
        // 删除不需要的字段
        delete productObj.priceHistory;
        delete productObj.marketPrice;
        delete productObj.shareRatio;
        delete productObj.platformProfit;
        delete productObj.__v;
        
        return productObj;
      });

      return {
        list: processedProducts,
        total,
        pageNum,
        pageSize
      };
    } catch (err) {
      console.error('获取H5商品列表失败:', err);
      throw err;
    }
  }
};

productSchema.pre('findOneAndUpdate', function(next) {
  next();
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product; 